package fiszki.namespace;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;


public class SetsActivity extends Activity {
	private ImageButton addNewSet;
    private ImageButton back;
    private ListView lvSets;
 
    private SetsDBAdapter setsDBAdapter;
    private Cursor setsCursor;
    private List<SetTasks> tasks;
    private SetTasksAdapter listAdapter;
	
    // OK
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().getAttributes().format = android.graphics.PixelFormat.RGBA_8888;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.sets);
        
        initUiElements();
        initListView();
        initButtonsOnClickListeners(); 
	}
	
	// OK
    private void initUiElements() { 	
        addNewSet = (ImageButton) findViewById(R.id.buttonAddSet);
        back = (ImageButton) findViewById(R.id.buttonBack);
        lvSets = (ListView) findViewById(R.id.lvSets);
    }
    
    // OK
    private void initListView() {
        fillListViewData();
        initListViewOnItemClick();
    }
    
    private void fillListViewData() {
        setsDBAdapter = new SetsDBAdapter(getApplicationContext());
        setsDBAdapter.open();
        getAllSets();
        listAdapter = new SetTasksAdapter(this, tasks);
        listAdapter.notifyDataSetChanged();
        lvSets.setAdapter(listAdapter);
        registerForContextMenu(lvSets);
    }
     
    private void getAllSets() {
        tasks = new ArrayList<SetTasks>();
        setsCursor = getAllEntriesFromDB();
        
        updateSetsList();
    }
     
    // OK
    private Cursor getAllEntriesFromDB() {
        setsCursor = setsDBAdapter.getAllSets();
        
        if(setsCursor != null) {
            startManagingCursor(setsCursor);
            setsCursor.moveToFirst();
        }
        
        return setsCursor;
    }
     
    private void updateSetsList() {
        if(setsCursor != null && setsCursor.moveToFirst()) {
            do {
                int id = setsCursor.getInt(SetsDBAdapter.ID_COLUMN);
                String name = setsCursor.getString(SetsDBAdapter.NAME_COLUMN);
                String questionLang = setsCursor.getString(SetsDBAdapter.QUESTIONLANG_COLUMN);
                String answerLang = setsCursor.getString(SetsDBAdapter.ANSWERLANG_COLUMN);
                
                tasks.add(new SetTasks(id, name, questionLang, answerLang));
            } 
            while(setsCursor.moveToNext());
        }
    }
    
    // OK
    @Override
    protected void onDestroy() {
        if(setsDBAdapter != null)
            setsDBAdapter.close();
        
        super.onDestroy();
    }
    
    private void initListViewOnItemClick() {  
        lvSets.setOnItemClickListener(new OnItemClickListener() {
            
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
             	SetTasks task = tasks.get(position);
            	Bundle setID = new Bundle();
            	setID.putInt("setID", task.getId());
            	Intent newIntent = new Intent(SetsActivity.this, SetContentActivity.class);
            	newIntent.putExtras(setID);
            	startActivityForResult(newIntent, 0);
            }
        });
    	
        lvSets.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
        	
			@Override
			public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        		 MenuInflater inflater = getMenuInflater();
        		 inflater.inflate(R.menu.menu_items, menu);
        	}
        });
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    	SetTasks task = tasks.get(info.position);
      
    	switch (item.getItemId()) {
      		case R.id.edit:
      			Bundle set = new Bundle();
            	set.putInt("setID", task.getId());
            	set.putString("name", task.getName());
            	set.putString("qLang", task.getQuestionLang());
            	set.putString("aLang", task.getAnswerLang());
            	
            	Intent newIntent = new Intent(SetsActivity.this, EditSetActivity.class);
            	newIntent.putExtras(set);
            	startActivityForResult(newIntent, 0);
            	finish();
      			return true;

      		case R.id.delete:
      			setsDBAdapter.deleteSet(task.getId());
      			updateListViewData();
      			return true;
    	  
      		default:
      			return super.onContextItemSelected(item);
    	}
    }
    
    private void updateListViewData() {
        setsCursor.requery();
        tasks.clear();
        updateSetsList();
        listAdapter.notifyDataSetChanged();
    }
    
    private void initButtonsOnClickListeners() { 	 	
    	addNewSet.setOnClickListener(new View.OnClickListener() {
            
			@Override
			public void onClick(View v) {
            	Intent i = new Intent(SetsActivity.this, AddSetActivity.class);
    			startActivity(i);
    			finish();
            }
        });
    	
    	back.setOnClickListener(new View.OnClickListener() {
            
			@Override
			public void onClick(View v) {
            	finish();
            }
        });
	} 
}
